class Notice < ActiveRecord::Base
  before_save :pick_random_design
  after_save :send_mail_about_new_postit
  
  #Foreign key is niet nodig, maar wordt wel aangeraden
  belongs_to :user, :class_name => 'User', :foreign_key => 'created_by'
  
  IMAGES_DIR = "#{RAILS_ROOT}/public/images/notices"
  IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'gif', 'png', 'bmp', 'tiff']
  
  def body_as_html
    body.nl2br
  end
  
  private
  def self.pick_random_image(except=nil)
    images = self.images
    
    images.delete_at(except.to_i - 1) if except != nil
    
    return rand(images.size)+1
  end
  
  def self.images
    images = Array.new
    
    extensions = IMAGE_EXTENSIONS.join(',')
    
    #Do a case insensitive search
    Dir.glob("#{IMAGES_DIR}/*.{#{extensions}}", File::FNM_CASEFOLD).each do | file |
      images << file
    end
    
    return images.sort
  end
  
  def pick_random_design
    #Find the last notice (don't want it to be the same design)
    last_design = Notice.find(:first, :order => 'id desc').design rescue nil
    
    self.design = Notice.pick_random_image(last_design)
  end
  
  def send_mail_about_new_postit
    users = User.get_all_active
    
    users.each do |user|
      Mailer.deliver_notify_about_postit(user, self) if user.mail_postit? and user != self.user
    end
  end
  
end
